from typing import Dict, List, Optional
import pandas as pd
import numpy as np
from datetime import datetime

from .trading_strategy import TradingStrategy
from analysis.market_analyzer import MarketAnalyzer
from risk.risk_manager import RiskManager

class MovingAverageStrategy(TradingStrategy):
    """均线交叉策略"""
    
    def __init__(self, market_analyzer: MarketAnalyzer, risk_manager: RiskManager,
                 short_window: int = 5, long_window: int = 20):
        """
        初始化均线交叉策略
        
        Args:
            market_analyzer: 市场分析器
            risk_manager: 风险管理器
            short_window: 短期均线周期
            long_window: 长期均线周期
        """
        super().__init__(market_analyzer, risk_manager)
        self.short_window = short_window
        self.long_window = long_window
        self.signals = {}  # 存储每个交易对的信号状态
        
    def calculate_indicators(self, data: pd.DataFrame) -> pd.DataFrame:
        """计算技术指标"""
        # 计算移动平均线
        data['short_ma'] = data['close'].rolling(window=self.short_window).mean()
        data['long_ma'] = data['close'].rolling(window=self.long_window).mean()
        
        # 计算金叉死叉信号
        data['signal'] = 0
        data.loc[data['short_ma'] > data['long_ma'], 'signal'] = 1
        data.loc[data['short_ma'] < data['long_ma'], 'signal'] = -1
        
        # 计算信号变化
        data['position_change'] = data['signal'].diff()
        
        return data
        
    def generate_signals(self, symbol: str) -> Dict:
        """生成交易信号"""
        # 获取市场数据
        market_data = self.market_analyzer.get_market_data(symbol)
        if market_data.empty:
            return {'action': 'hold', 'reason': 'no_data'}
            
        # 计算指标
        signals = self.calculate_indicators(market_data)
        
        # 获取最新信号
        latest = signals.iloc[-1]
        prev_signal = self.signals.get(symbol, 0)
        
        # 检查风险控制
        if self.risk_manager.should_stop_trading():
            return {'action': 'hold', 'reason': 'risk_control'}
            
        # 检查止损
        if symbol in self.positions and self.risk_manager.should_stop_loss(
            symbol, latest['close']):
            return {'action': 'sell', 'reason': 'stop_loss'}
            
        # 生成交易信号
        if latest['position_change'] > 0:  # 金叉
            self.signals[symbol] = 1
            return {
                'action': 'buy',
                'price': latest['close'],
                'reason': 'golden_cross',
                'indicators': {
                    'short_ma': latest['short_ma'],
                    'long_ma': latest['long_ma']
                },
                'timestamp': latest.name
            }
        elif latest['position_change'] < 0:  # 死叉
            self.signals[symbol] = -1
            return {
                'action': 'sell',
                'price': latest['close'],
                'reason': 'death_cross',
                'indicators': {
                    'short_ma': latest['short_ma'],
                    'long_ma': latest['long_ma']
                },
                'timestamp': latest.name
            }
            
        return {'action': 'hold', 'reason': 'no_signal'}
        
    def execute_trade(self, symbol: str, signal: Dict) -> bool:
        """执行交易"""
        try:
            if signal['action'] == 'buy' and symbol not in self.positions:
                # 计算仓位大小
                available_balance = self._get_available_balance()
                position_size = self.risk_manager.calculate_position_size(
                    available_balance,
                    signal['price'],
                    self.market_analyzer.calculate_volatility(symbol)
                )
                
                # 检查仓位是否符合风险控制
                if not self.risk_manager.check_position_size(
                    symbol, position_size, signal['price']):
                    return False
                    
                # 执行买入
                self._execute_order(symbol, 'buy', position_size)
                return True
                
            elif signal['action'] == 'sell' and symbol in self.positions:
                # 执行卖出
                position = self.positions[symbol]
                self._execute_order(symbol, 'sell', position['size'])
                return True
                
            return False
            
        except Exception as e:
            print(f"Error executing trade: {e}")
            return False
